<template>
  <div class="menu-container">
    <el-card class="menu-card">
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="handleAdd">新增菜单</el-button>
        </div>
      </template>
      
      <!-- 菜单树形表格 -->
      <el-table
        :data="menuList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="title" label="菜单名称" width="220" />
        <el-table-column prop="icon" label="图标" width="100" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" width="180" />
        <el-table-column prop="component" label="组件路径" width="180" />
        <el-table-column prop="permission" label="权限标识" width="180" />
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="visible" label="可见" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.visible ? 'success' : 'info'">
              {{ row.visible ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="success" size="small" @click="handleAddChild(row)">新增子菜单</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuOptions"
            :props="{ label: 'title', value: 'id', children: 'children' }"
            placeholder="请选择上级菜单"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="title">
          <el-input v-model="menuForm.title" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3" label="图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称">
            <template #append>
              <el-button @click="handleSelectIcon">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="menuForm.type === 2" label="路由路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item v-if="menuForm.type === 2" label="组件路径" prop="component">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 1" label="权限标识" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="显示排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3" label="路由名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入路由名称" />
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3" label="是否显示" prop="visible">
          <el-radio-group v-model="menuForm.visible">
            <el-radio :label="true">显示</el-radio>
            <el-radio :label="false">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3" label="是否外链" prop="isExternal">
          <el-radio-group v-model="menuForm.isExternal">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3 && menuForm.isExternal" label="外链地址" prop="externalUrl">
          <el-input v-model="menuForm.externalUrl" placeholder="请输入外链地址" />
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3" label="是否缓存" prop="keepAlive">
          <el-radio-group v-model="menuForm.keepAlive">
            <el-radio :label="true">缓存</el-radio>
            <el-radio :label="false">不缓存</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图标选择对话框 -->
    <el-dialog v-model="iconDialogVisible" title="选择图标" width="800px">
      <div class="icon-list">
        <div
          v-for="icon in iconList"
          :key="icon"
          class="icon-item"
          @click="handleIconSelect(icon)"
        >
          <el-icon>
            <component :is="icon" />
          </el-icon>
          <div class="icon-name">{{ icon }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 菜单接口定义
interface MenuItem {
  id?: number
  parentId?: number | null
  type: number
  title: string
  icon?: string
  path?: string
  component?: string
  permission?: string
  sort: number
  name?: string
  visible: boolean
  isExternal: boolean
  externalUrl?: string
  keepAlive: boolean
  children?: MenuItem[]
}

// 响应式数据
const menuList = ref<MenuItem[]>([])
const menuOptions = ref<MenuItem[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const iconDialogVisible = ref(false)
const menuFormRef = ref<FormInstance>()
const isEdit = ref(false)
const currentParentId = ref<number | null>(null)

// 菜单表单
const menuForm = reactive<MenuItem>({
  parentId: null,
  type: 2,
  title: '',
  icon: '',
  path: '',
  component: '',
  permission: '',
  sort: 0,
  name: '',
  visible: true,
  isExternal: false,
  externalUrl: '',
  keepAlive: true
})

// 表单验证规则
const menuRules: FormRules = {
  type: [{ required: true, message: '请选择菜单类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
  component: [{ required: true, message: '请输入组件路径', trigger: 'blur' }],
  permission: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入显示排序', trigger: 'blur' }]
}

// 图标列表
const iconList = [
  'HomeFilled', 'Setting', 'User', 'Lock', 'Key', 'Monitor', 'DataLine', 
  'Document', 'Folder', 'FolderOpened', 'Menu', 'Grid', 'List', 'Star',
  'Location', 'Edit', 'Delete', 'Plus', 'Search', 'Refresh', 'Share',
  'Upload', 'Download', 'Message', 'Notification', 'Warning', 'Error'
]

// 初始化数据
onMounted(() => {
  fetchMenuList()
})

// 获取菜单列表
const fetchMenuList = async () => {
  try {
    // 模拟API请求
    setTimeout(() => {
      menuList.value = [
        {
          id: 1,
          parentId: null,
          type: 1,
          title: '系统管理',
          icon: 'Setting',
          path: '/system',
          sort: 1,
          name: 'system',
          visible: true,
          isExternal: false,
          keepAlive: true,
          children: [
            {
              id: 2,
              parentId: 1,
              type: 2,
              title: '用户管理',
              icon: 'User',
              path: '/system/user',
              component: 'views/system/UserView.vue',
              permission: 'system:user:list',
              sort: 1,
              name: 'user',
              visible: true,
              isExternal: false,
              keepAlive: true
            },
            {
              id: 3,
              parentId: 1,
              type: 2,
              title: '角色管理',
              icon: 'UserFilled',
              path: '/system/role',
              component: 'views/system/RoleView.vue',
              permission: 'system:role:list',
              sort: 2,
              name: 'role',
              visible: true,
              isExternal: false,
              keepAlive: true
            }
          ]
        },
        {
          id: 4,
          parentId: null,
          type: 1,
          title: '内容管理',
          icon: 'Document',
          path: '/content',
          sort: 2,
          name: 'content',
          visible: true,
          isExternal: false,
          keepAlive: true,
          children: [
            {
              id: 5,
              parentId: 4,
              type: 2,
              title: '文章管理',
              icon: 'Document',
              path: '/content/article',
              component: 'views/content/ArticleView.vue',
              permission: 'content:article:list',
              sort: 1,
              name: 'article',
              visible: true,
              isExternal: false,
              keepAlive: true
            }
          ]
        }
      ]
      
      // 构建菜单选项树
      menuOptions.value = buildMenuOptions(menuList.value)
    }, 500)
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    ElMessage.error('获取菜单列表失败')
  }
}

// 构建菜单选项树
const buildMenuOptions = (menus: MenuItem[]): MenuItem[] => {
  return menus.map(menu => ({
    id: menu.id,
    title: menu.title,
    children: menu.children ? buildMenuOptions(menu.children) : []
  }))
}

// 新增菜单
const handleAdd = () => {
  resetForm()
  isEdit.value = false
  dialogTitle.value = '新增菜单'
  dialogVisible.value = true
}

// 新增子菜单
const handleAddChild = (row: MenuItem) => {
  resetForm()
  isEdit.value = false
  dialogTitle.value = '新增子菜单'
  menuForm.parentId = row.id
  currentParentId.value = row.id || null
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row: MenuItem) => {
  resetForm()
  isEdit.value = true
  dialogTitle.value = '编辑菜单'
  Object.assign(menuForm, row)
  currentParentId.value = row.parentId || null
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = (row: MenuItem) => {
  ElMessageBox.confirm('确认删除该菜单及其子菜单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 模拟删除操作
      setTimeout(() => {
        ElMessage.success('删除成功')
        fetchMenuList()
      }, 500)
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!menuFormRef.value) return
  
  await menuFormRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交操作
      setTimeout(() => {
        if (isEdit.value) {
          ElMessage.success('修改成功')
        } else {
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchMenuList()
      }, 500)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (menuFormRef.value) {
    menuFormRef.value.resetFields()
  }
  Object.assign(menuForm, {
    parentId: currentParentId.value,
    type: 2,
    title: '',
    icon: '',
    path: '',
    component: '',
    permission: '',
    sort: 0,
    name: '',
    visible: true,
    isExternal: false,
    externalUrl: '',
    keepAlive: true
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetForm()
  currentParentId.value = null
}

// 选择图标
const handleSelectIcon = () => {
  iconDialogVisible.value = true
}

// 确认选择图标
const handleIconSelect = (icon: string) => {
  menuForm.icon = icon
  iconDialogVisible.value = false
}
</script>

<style scoped>
.menu-container {
  padding: 20px;
}

.menu-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operation-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
  justify-content: center;
}

.icon-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.icon-item:hover {
  background-color: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.icon-name {
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  word-break: break-all;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .menu-container {
    padding: 10px;
  }
  
  .icon-item {
    width: 60px;
    height: 60px;
  }
  
  .operation-buttons {
    flex-direction: column;
    gap: 3px;
  }
}
</style>